package xrate

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xcache"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 创建星级信息
//
//	stat	星级信息
//	uid		用户ID
func StartCreate(stat *Start, uid uint) error {
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	if uid <= 0 {
		return xerror.New("用户ID不能为空")
	}
	if stat.Name == "" {
		return xerror.New("星级名称不能为空")
	}
	if stat.Rate <= 0 {
		return xerror.New("中奖率不能为空")
	}
	if stat.BatchId == 0 {
		return xerror.New("所属批次不能为空")
	}
	if stat.UserId == 0 {
		stat.UserId = uid
	}
	if stat.CreatedAt == "" {
		stat.CreatedAt = time.Now().Format(time.DateTime)
	}
	stat.UpdatedAt = time.Now().Format(time.DateTime)
	err := _default.DB.Save(stat).Error
	if err != nil {
		return err
	}
	// 缓存写入
	xcache.Remove(xcache.Key("xrate.rate_batch", stat.BatchId))
	xcache.SetStruct(xcache.Key("xrate.start_info", stat.ID), stat)
	return nil
}
